/* ===== scopelist ===== ：景点库*/
myApp.onPageInit('scopelist', function (page) {
	console.log('scopelist');
	var scopecityid = global_cityid;
	
	//下拉加载的参数初始化
    // Loading flag
    var loading = false;
    // Append items per load
	var scopelistitemsPerLoad = scopepageitem;
    
    //city
    $$.getJSON(url_get_city, {}, function (ajaxresult) {
        //获取city数据
        if(ajaxresult.code==1){
            var data_playingmethodcity = ajaxresult.data;
            var html_playingmethodcity = myApp.playingMethodCityTemplate(data_playingmethodcity);
            html_playingmethodcity="<li><div class='row' style='margin:5px;justify-content: flex-start;'><div class='col-33' style='width: calc(100%/3);margin-bottom: 0.5vh;margin-top: 0.5vh;'>" +
    		"<a href='#' class='button btn_item size_12' style='width:90%;margin:0 auto;' " +
    		"data-city='不限' data-id='0'>不限</a></div></li>"+html_playingmethodcity;
            $$('div.scopecity ul').html(html_playingmethodcity);
            
        }else{
            ajaxfail(ajaxresult.msg);
        }
        //选定全局城市
        var activedom = ".scopecity a.btn_item[data-id='" + scopecityid.toString() + "']";
        $$(activedom).addClass('active');
        //更新标题
        var city = '';
        city=$$(activedom).html(); 
        $$('.scopecity_title span').html(city);
        
        //点击city,type
        $$('.scopecity a.btn_item').click(function(){
            $$('.scopecity a.btn_item').removeClass('active');
            $$(this).addClass('active');
            var cityid=$$(this).data('id');
            
            //更新标题
            if(cityid=='0'){
            	city='城市';
            }else{city=$$(this).html();} 
            $$('.scopecity_title span').html(city);
            //选择城市重置景点类型
			var type='景点类型';
			$$('.scopetype_title span').html(type);

            //更新type
            $$.getJSON(url_get_scopetype, {cityId:cityid}, function (ajaxresult) {
        		if(ajaxresult.code==1){
        			var data_scopetypetag = ajaxresult.data;
        			var html_scopetypetag = myApp.scopeTypeTagTemplate(data_scopetypetag);
            		$$('.scopetype ul').html(html_scopetypetag);

                    //click
                    $$('.scopetypetag a.btn_item').on('click',function(){
                        $$('.scopetypetag a.btn_item').removeClass('active');
                        $$(this).addClass('active');
                        //更新标题
                        var type = '';
                        if($$(this).data('id')=='0'){
                        	type='景点类型';
                        }else{type=$$(this).html();} 
                        $$('.scopetype_title span').html(type);
                        //刷新页面
                        getscopelist(0,scopepageitem,'refresh');
                    });
        		}else{
        			ajaxfail(ajaxresult.msg);
        		}
            });
            
            //刷新页面
            getscopelist(0,scopepageitem,'refresh');           
        });
    }); 
    
    //type
	$$.getJSON(url_get_scopetype, {cityId:scopecityid}, function (ajaxresult) {
		if(ajaxresult.code==1){
			var data_scopetypetag = ajaxresult.data;
            console.log(data_scopetypetag);
			var html_scopetypetag = myApp.scopeTypeTagTemplate(data_scopetypetag);
    		$$('.scopetype ul').html(html_scopetypetag);

            //click
            $$('.scopetypetag a.btn_item').on('click',function(){
                $$('.scopetypetag a.btn_item').removeClass('active');
                $$(this).addClass('active');
                //更新标题
                var type = '';
                if($$(this).data('id')=='0'){
                	type='景点类型';
                }else{type=$$(this).html();} 
                $$('.scopetype_title span').html(type);
                //刷新页面
                getscopelist(0,scopepageitem,'refresh');
            });
		}else{
			ajaxfail(ajaxresult.msg);
		}
    });
	
	//list初始化
    $$.getJSON(url_get_scopelist, {city:scopecityid,offset:0,limit:scopepageitem,type:0}, function (ajaxresult) {
        if(ajaxresult.code==1){
            var data_scopelist = ajaxresult.data;
            var html_scopelist = myApp.scopeListTemplate(data_scopelist);
            $$('#scopelist .div_scopelist').html(html_scopelist);
            
            //页面第一次加载
    		// Last loaded index
            var lastIndex=$$('.div_scopelist .scopeitem').length;
			$$("input[name='scope_lastIndex']").val(lastIndex);
        }else{
            ajaxfail(ajaxresult.msg);
        }
    });
    
	//滚动加载
    // 注册'infinite'事件处理函数
    $$('#scopelist .infinite-scroll').on('infinite', function () {
    	// 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        // 模拟1s的加载过程
        setTimeout(function () {
           // 重置加载flag
           loading = false;
           // 读取上次加载的索引
           var lastIndex = $$("input[name='scope_lastIndex']").val();
           //生成新的条目
           getscopelist(lastIndex,scopelistitemsPerLoad,'append');           
         }, 1000);
    });
  //subnav的收放 
    $$(".scopetype_title").click(function(){
    	var stop=false;
    	//关闭其他
    	if ($$('.scopecity').hasClass('grade-w-roll')){
            $$('.scopecity').removeClass('grade-w-roll');
            stop=true;
        };
        //打开或开启自身
        if ($$('.scopetype').hasClass('grade-w-roll')) {
            $$('.scopetype').removeClass('grade-w-roll');
            $$("#scopelist").removeClass('with-shadow');
        }else {
        	if(stop){
        		setTimeout("$$('.scopetype').addClass('grade-w-roll')",500);
        	}else{
        		$$("#scopelist").addClass('with-shadow');
                $$('.scopetype').addClass('grade-w-roll');
        	}
        }        
    });    
    $$(".scopecity_title").click(function(){
    	var stop=false;
    	if ($$('.scopetype').hasClass('grade-w-roll')){
            $$('.scopetype').removeClass('grade-w-roll');
            stop=true;
        };
        if ($$('.scopecity').hasClass('grade-w-roll')) {
            $$('.scopecity').removeClass('grade-w-roll');
            $$("#scopelist").removeClass('with-shadow');
        }else {
        	if(stop){
        		setTimeout("$$('.scopecity').addClass('grade-w-roll')",500);
        	}else{
        		$$("#scopelist").addClass('with-shadow');
                $$('.scopecity').addClass('grade-w-roll');
        	}            
        }        
    });          
});

/* ===== scopedetail ===== ：景点库*/
myApp.onPageInit('scopedetail', function (page) {
	console.log('scopedetail');
    
	var scopedetailswiper = new Swiper('.swiper-scopedetail', {
		pagination:".swiper-pagination-scopedetail",
		loop:true,
	    autoplay:5000,
	    autoplayDisableOnInteraction:false
	});
	
	/*---地图---*/
    var lat=$$('#scopedetail .addrimg').data('lat');
	var lng=$$('#scopedetail .addrimg').data('lng');	
	//设置地图中心
	if(lat&&lng){
		var myLatlng=new google.maps.LatLng(lat,lng);
	}else{
		//默认地图中心为巴黎
		var myLatlng=new google.maps.LatLng(48.8587741, 2.2074729);
	}
    
    var mapOptions = {
        center: myLatlng,
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl:false,
	    zoomControl:false,
	    streetViewControl:false
	};
    //googlemap(address,myLatlng,infowidowcontent,mapcontainer,mapOptions)
    //address='', myLatlng!='' 根据latlng确定位置
    //address!='', myLatlng='' 根据address查询地址
    
    googlemap('',myLatlng,'',$$('#scopedetail .addrimg')[0],mapOptions);
    
    $$('#scopedetail .zan').click(function(){
    	$$(this).transform('rotate(10deg)');
    	$$(this).transition(300);
    	setTimeout(function(){
    		$$('#scopedetail .zan').transform('rotate(-10deg)');
    		$$('#scopedetail .zan').transition(600);
    	},300);
    	setTimeout(function(){
    		$$('#scopedetail .zan').transform('rotate(0deg)');
    		$$('#scopedetail .zan').transition(300);
    	},900);
    });

    $$('#scopedetail .scoperemark').on('click',function(){
        var id = $$(this).data("id");
        var name = $$(this).data("name");
        //验证是否登陆
        checklogin();
        if(!global_login_state){
            mainView.router.load({
                "url":"welcome.html",
            });
        }else{
        	var res=isscenicremarked(id);
        	//没有评论过，跳转评论页
        	if(res){
        		//跳转登陆页会导致之后返回到景点详情页没有数据
        		mainView.router.load({
                    "url":"scoperemark.html",
                   "context":{'id':id,'name':name}
                });
        		//ajaxfail('请先登录再进行评论');
        	}else{
        		ajaxfail('您已评论过该景点');
        	}
        }
    }); 
});

/* ===== scoperemark =====：评论 */
myApp.onPageInit('scoperemark', function (page) {
    console.log("scoperemark");
    //添加按钮触发<input file>，选择图片
    $$("#scoperemark ").on('touchend','.remark_photo',function(){
        return $$("#scoperemark .imgfile").click();
    });
    //选择图片后触发change事件
    $$("#scoperemark .imgfile").on('change',function(e){
    	//避免多次alert
    	var errorflag = false;
    	/*获取<input file>中的FileList对象或者dataTransfer对象的文件*/
    	/*<input file>标签中有mutiple属性，一次可以选择多张图保存到<input file>中*/
        var files = e.target.files||e.dataTransfer.files;
        for(var i=0;i<files.length;i++){
        	//检查图片大小和类型
             if(files[i]){
            	 console.log(files[i].type);
            	 var filesize=Math.round(files[i].size/1024/1024*100)/100;//单位MB
                 if(filesize>5){
                	 if(!errorflag){
                		 ajaxfail("图片大小不要超过5M");
                		 errorflag=true;
                	 }                 	                 	 
                 }else{
                	 /*为此次添加的文件创建base64码*/
                	 var reader = new FileReader();
                     reader.readAsDataURL(files[i]);
                     reader.onload=function(){
                        //生成缩略图
                    	var result=$$("#scoperemark .photo");
                    	console.log(this.result);
                        var thumbhtml='<div class="col-25 img_selected" style="text-align:left;width: calc(100%/4);"><img src="' + this.result +'" style="width:80%;"/></div>';
                        result.html(thumbhtml+ result.html());                        
                     }
                 }                                  
            }                
        }      
    });
    
    $$('#scoperemark .submit_remark').on('click',function(){
        var id = $$(this).data('id');
        var remark = $$('#scoperemark textarea').val();
        var filelist = [];
        $$('#scoperemark .img_selected img').each(function(){
        	filelist.push($$(this).attr('src'));
        });
        //验证是否输入评论
        if(!remark){
        	ajaxfail("请输入评论");
        	return;
        }else{
        	if(remark.length>500){
        		ajaxfail("请控制评论在500字以内");
        		return;
        	}
        }
        //添加评论
    	$$.ajax({
            url:url_post_addscoperemark,
            data:{
                'scenic_id':id,
                'comments':remark,
                'images':filelist
            },
            dataType:'json',
            method:"POST",
            xhrFields:{withCredentials:true},
            success:function(ajaxresult){
                if(ajaxresult.code==1){
                	//评论成功，跳转景点详情页
                    $$.getJSON(url_get_scopedetail, {id:id}, function (ajaxresult) {
                        if(ajaxresult.code==1){
                            mainView.router.load({
                                "url":"scopedetail.html",
                                "context":ajaxresult.data
                            });                     
                        }else{
                            ajaxfail(ajaxresult.msg);
                        }
                    });                   
                }else{
                    ajaxfail(ajaxresult.msg);
                }

            }
        });        
    });
});
